package com.shuda.business.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.channel.dto.DownstreamChannelDTO;
import com.shuda.business.channel.dto.DownstreamChannelQueryDTO;
import com.shuda.business.channel.entity.DownstreamChannelEntity;
import com.shuda.business.channel.mapper.DownstreamChannelMapper;
import com.shuda.business.channel.service.DownstreamChannelService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.dto.PageResult;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 下游渠道服务实现类
 */
@Service
public class DownstreamChannelServiceImpl extends ServiceImpl<DownstreamChannelMapper, DownstreamChannelEntity> 
        implements DownstreamChannelService {

    @Autowired
    private DownstreamChannelMapper downstreamChannelMapper;

    @Override
    public PageResult<DownstreamChannelDTO> getDownstreamChannelPage(PageDTO pageDTO, DownstreamChannelQueryDTO queryDTO) {
        Page<DownstreamChannelEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        LambdaQueryWrapper<DownstreamChannelEntity> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getChannelName())) {
            wrapper.like(DownstreamChannelEntity::getChannelName, queryDTO.getChannelName());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelCode())) {
            wrapper.eq(DownstreamChannelEntity::getChannelCode, queryDTO.getChannelCode());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelType())) {
            wrapper.eq(DownstreamChannelEntity::getChannelType, queryDTO.getChannelType());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelStatus())) {
            wrapper.eq(DownstreamChannelEntity::getChannelStatus, queryDTO.getChannelStatus());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge(DownstreamChannelEntity::getCreateTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le(DownstreamChannelEntity::getCreateTime, queryDTO.getEndTime());
        }
        
        wrapper.orderByDesc(DownstreamChannelEntity::getCreateTime);
        
        IPage<DownstreamChannelEntity> result = downstreamChannelMapper.selectPage(page, wrapper);
        
        List<DownstreamChannelDTO> dtoList = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageResult<>(dtoList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public DownstreamChannelDTO getDownstreamChannelById(Long id) {
        DownstreamChannelEntity entity = downstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("下游渠道不存在");
        }
        return convertToDTO(entity);
    }

    @Override
    public Long createDownstreamChannel(DownstreamChannelDTO dto) {
        DownstreamChannelEntity entity = convertToEntity(dto);
        entity.setChannelStatus("enabled");
        entity.setCreateBy(SecurityUtils.getCurrentUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setDeleted(0);
        
        downstreamChannelMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateDownstreamChannel(Long id, DownstreamChannelDTO dto) {
        DownstreamChannelEntity existingEntity = downstreamChannelMapper.selectById(id);
        if (existingEntity == null) {
            throw new BusinessException("下游渠道不存在");
        }
        
        DownstreamChannelEntity entity = convertToEntity(dto);
        entity.setId(id);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        
        downstreamChannelMapper.updateById(entity);
    }

    @Override
    public void deleteDownstreamChannel(Long id) {
        DownstreamChannelEntity entity = downstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("下游渠道不存在");
        }
        
        entity.setDeleted(1);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        downstreamChannelMapper.updateById(entity);
    }

    @Override
    public void batchDeleteDownstreamChannel(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<DownstreamChannelEntity> entities = downstreamChannelMapper.selectBatchIds(ids);
            String currentUsername = SecurityUtils.getCurrentUsername();
            LocalDateTime now = LocalDateTime.now();
            
            for (DownstreamChannelEntity entity : entities) {
                entity.setDeleted(1);
                entity.setUpdateBy(currentUsername);
                entity.setUpdateTime(now);
                downstreamChannelMapper.updateById(entity);
            }
        }
    }

    @Override
    public void updateDownstreamChannelStatus(Long id, String status) {
        DownstreamChannelEntity entity = downstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("下游渠道不存在");
        }
        
        entity.setChannelStatus(status);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        downstreamChannelMapper.updateById(entity);
    }

    @Override
    public List<DownstreamChannelDTO> getEnabledDownstreamChannelList() {
        LambdaQueryWrapper<DownstreamChannelEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DownstreamChannelEntity::getChannelStatus, "enabled")
                .eq(DownstreamChannelEntity::getDeleted, 0)
                .orderByDesc(DownstreamChannelEntity::getPriority)
                .orderByDesc(DownstreamChannelEntity::getCreateTime);
        
        List<DownstreamChannelEntity> entities = downstreamChannelMapper.selectList(wrapper);
        return entities.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private DownstreamChannelDTO convertToDTO(DownstreamChannelEntity entity) {
        DownstreamChannelDTO dto = new DownstreamChannelDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private DownstreamChannelEntity convertToEntity(DownstreamChannelDTO dto) {
        DownstreamChannelEntity entity = new DownstreamChannelEntity();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}